#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_flask_database_sqlalchemy.py
# author:Jackiex
# datetime:2023/5/25 14:03
# software: PyCharm

"""
   利用SQLAlchemy框架来访问数据库
"""

from flask import Flask, render_template
from flask_bootstrap import Bootstrap

from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

bootstrap = Bootstrap(app)

app.config.from_object("config")
db = SQLAlchemy(app)


class User(db.Model):
    # 表的名字:
    __tablename__ = 'user3'

    # 表的结构:
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)


def model_to_dict(result):
    from collections.abc import Iterable
    # 转换完成后，删除 '_sa_instance_state' 特殊属性
    try:
        if isinstance(result, Iterable):
            tmp = [dict(zip(res.__dict__.keys(), res.__dict__.values())) for res in result]
            for t in tmp:
                t.pop('_sa_instance_state')
        else:
            tmp = dict(zip(result.__dict__.keys(), result.__dict__.values()))
            tmp.pop('_sa_instance_state')
        return tmp
    except BaseException as e:
        print(e.args)
        raise TypeError('Type error of parameter')


@app.route('/userlist')
def user_list():
    users = db.session.query(User).all()

    # 将查询到的数据转换成字典
    users_dict = model_to_dict(users)

    return render_template('data.html', mydict=users_dict)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
